import datetime
import time
import pytz

FMT = '%Y-%m-%d %H:%M:%S.%f %z'

utc_tz = pytz.timezone('UTC')
china_tz = pytz.timezone('Asia/Shanghai')
with open('x_log_datetime_by_datetime.tmp.txt', 'a+') as xfile:
    # xutc_now = datetime.datetime.utcnow()
    xutc_now = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=0)))
    xfile.write(xutc_now.strftime(FMT) + '\n')
    xnow = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=8)))
    xfile.write(xnow.strftime(FMT) + '\n')
    xfile.flush()

    xfile.seek(0)
    while True:
        xline = xfile.readline()
        if '' == xline:
            break
        xline = xline[:-1]
        print(xline, '=>')
        try:
            xdt = datetime.datetime.strptime(xline, FMT)
            print('xdt', xdt.strftime(FMT))
            xdt_utc = xdt.astimezone(utc_tz)
            print('xdt_utc', xdt_utc.strftime(FMT))
        except ValueError as ex:
            print(repr(ex))

